#!/usr/bin/python
# -*- coding: utf-8 -*-

# slack-backup Tiny BackUp Manager 0.01
# Qt4 GUI

import sys
import zipfile
from datetime import date
import ConfigParser

from PyQt4 import QtGui, QtCore, uic
from zipi import *
from utils import *


class Window(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        uic.loadUi("window.ui", self)
        self.gcancel = False
        self.last_dir = ''
        self.txt_1.setText(zipiname())
        self.txt_2.setText('.*')
        self.ctrblock(False)

    def skip(f):

        def inner(*args, **kwargs):
            if len(args) == 1:
                f(*args, **kwargs)
        return inner

    @skip
    def on_bt_1_clicked(self, b=None): # Add Button
        qf = QtGui.QFileDialog
        t = self.tr("Select Directory")
        fname = unicode(qf.getExistingDirectory(self, t, self.last_dir))
        if fname:
            self.lst.addItem(fname)
            self.last_dir = fname

    @skip
    def on_bt_2_clicked(self, b=None): # Remove
        self.lst.takeItem(self.lst.currentRow())

    @skip
    def on_bt_3_clicked(self, b=None): # Start BackUp Button
        self.ctrblock(True)
        self.pb_1.setMaximum(100)
        zzip = Slack_Zip()
        zzip.zipName = str(self.txt_1.text())
        zzip.zipExtensions = str(self.txt_2.text())
        zzip.Destination = str(self.txt_3.text())
        zzip.zipMode = 'a'

        for i in range(self.lst.count()):
            zzip.zipPath.append(str(self.lst.item(i).text()))

        zzip.start()
        while zzip.isAlive():
            QtCore.QCoreApplication.instance().processEvents()
            zzip.Halt = self.gcancel
            self.pb_1.setValue(zzip.PBProgress)
            self.lbl_p.setText(self.parse_status(zzip.Status))
            self.lbl_s.setText(zzip.CurrFile)

        self.lbl_p.setText(self.parse_status(zzip.Status))
        self.lbl_s.setText("")
        self.pb_1.setValue(self.pb_1.maximum())
        self.ctrblock(False)
        self.gcancel = False
        zzip = None

    @skip
    def on_bt_4_clicked(self, b=None): # Cancel Button
        self.gcancel = True

    @skip
    def on_bt_5_clicked(self, b=None): # Destination Path Button
        qf = QtGui.QFileDialog
        t = self.tr("Select Destination Directory")
        fname = unicode(qf.getExistingDirectory(self, t, self.last_dir))
        if fname:
            self.txt_3.setText(fname)
            self.last_dir = fname

    @skip
    def on_action_open_triggered(self): # Open BackUp Configuration File
        qf = QtGui.QFileDialog
        t = self.tr("Select BackUp Configuration File")
        d = self.tr("BackUp Configuration File (*.mrt)")
        fname = unicode(qf.getOpenFileName(self, t, "", (d)))
        if fname:
            self.load_cfg(fname)

    @skip
    def on_action_save_triggered(self): # Save BackUp Configuration File
        qf = QtGui.QFileDialog
        t = self.tr("Select BackUp Configuration Destination")
        d = self.tr("BackUp Configuration File (*.mrt)")
        fname = unicode(qf.getSaveFileName(self, t, "", (d)))
        if fname:
            self.save_cfg(fname)

    @skip
    def on_action_quit_triggered(self): # Exit application
        QtGui.QApplication.quit()

    @skip
    def on_action_about_triggered(self):
        t = "slack-backup Tiniy-BackUp Manager\n"
        d = self.tr("Developed by mRt.\n\n")
        m = "martincerdeira@gmail.com"
        self.msg_pop(self.tr("About"), t + d + m)

    def save_cfg(self, path): # Saves configurations from file
        cfg = ConfigParser.ConfigParser()
        cfg.add_section("ZipFile")
        cfg.set("ZipFile", "destination", self.txt_3.text())
        cfg.set("ZipFile", "extensions", self.txt_2.text())
        cfg.add_section("Paths")
        for i in range(self.lst.count()):
            cfg.set("Paths", "f" + str(i + 1), str(self.lst.item(i).text()))

        if not e_endsw(path, ".mrt"):
            path = path + ".mrt"

        f = open(path, "w")
        cfg.write(f)
        f.close()

    def load_cfg(self, path): # Loads configurations from file
        cfg = ConfigParser.ConfigParser()
        cfg.read(path)
        try:
            self.txt_2.setText(cfg.get("ZipFile", "extensions"))
            self.txt_3.setText(cfg.get("ZipFile", "destination"))
            itm = cfg.items("Paths")
            for i in itm:
                self.lst.addItem(i[1])
        except:
            m = self.tr("Seems like your configuration file is broken")
            self.msg_pop(self.tr("Error"), m)

    def ctrblock(self, value):
        self.bt_1.setEnabled(not value)
        self.bt_2.setEnabled(not value)
        self.bt_3.setEnabled(not value)
        self.bt_4.setEnabled(value) # Cancel is always opposite
        self.bt_5.setEnabled(not value)
        self.txt_1.setEnabled(not value)
        self.txt_2.setEnabled(not value)
        self.txt_3.setEnabled(not value)

    def msg_pop(self, title, message):
        w = QtGui.QWidget()
        msg = QtGui.QMessageBox
        msg.information(w, title, message)

    def parse_status(self, st):
        if st == -1:
            return self.tr("Idle")
        elif st == 0:
            return self.tr("Processing")
        elif st == 1:
            return self.tr("Cancelled by user")
        elif st == 2:
            return self.tr("Finished!")


def main():
    app = QtGui.QApplication(sys.argv)
    locale = unicode(QtCore.QLocale.system().name())
    translator = QtCore.QTranslator()
    translator.load(os.path.join(os.path.abspath(
                 os.path.dirname(__file__)),
                 "window_" + unicode(locale)))
    app.installTranslator(translator)
    qtTranslator = QtCore.QTranslator()
    qtTranslator.load("qt_" + locale,
             QtCore.QLibraryInfo.location(
                 QtCore.QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)
    w = Window()
    w.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
